package com.cetcs.kmga.dataManager.entity.dataManager.vo;

import com.cetcs.kmga.dataManager.util.CheckIpUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Ip集合
 * Created by root on 2017/9/21.
 */
public class IpSettingVo {

    /**
     * 逗号分隔符
     */
    final static String COMMA  =",";
    /**
     * IP段可能以横线为分隔符
     */
    final static char SPLITMARK_LINE = '-';
    /**
     * IP段可能以波浪线为分隔符
     */
    final static char SPLITMARK_BOTLINE = '~';
//////////////保存需要的参数
    private int id;

    @javax.validation.constraints.Pattern(regexp = "^[\\u4E00-\\u9FA5A-Za-z0-9_-]+$", message= "名称输入不符合规范，请重新输入")
    private String name;

    //参数需要一个字段接受包含零散IP和IP集合的字段,前端查询列表需要
    private String ip;

//////////////保存需要的参数

    @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss")
    private Date updateTime;
///////// 数据库存储字段 ////////
    //零散IP，每个值都为单独一个ip，逗号隔开.如172.28.3.1,172.28.3.4
    private String ipSet;

    //IP集合，每个值都为一个ip段，逗号隔开。段之间的标识为’-‘。如172.28.10.172-172.28.10.192
    private String ipSegm;
    ///////// 数据库存储字段 ////////

    //前端查询时ip要求数组格式
    private String[] ips;
    //前端页面序号:page*Nupagem + 记录在当前页序号
    private int num;

    /**
     * 输入检查
     * @return
     */
    public String checkInput(){
        if(StringUtils.isEmpty(name)) return "名称不能为空";
        return checkIpFormat();
    }

    /**
     * 检查ip字段内容是否符合IP格式,如果符合就重新设置零散IP和IP集合<br></>
     * 将ip中的内容以英文逗号分隔成IP数组,将IP数组判断是零散IP还是IP集合
     *
     * @return 重设消息,如果为null,说明格式正确
     */
    private String checkIpFormat(){
        String message = null;
        if(StringUtils.isEmpty(ip)) return "ip不能为空";
        ip = replaceSpecialStr(ip.trim());
        String[] ipArray = ip.trim().split(COMMA);
        StringBuffer ipSetBuffer = new StringBuffer();
        StringBuffer ipSegmBuffer = new StringBuffer();
        for(String ipItem : ipArray){
            if(checkIsIpSegm(ipItem)){//IP段
                String[] ips = ipItem.split(String.valueOf(querySplitChar(ipItem)));
                for(String ip : ips){
                    if(!CheckIpUtil.isIpValid(ip)){
                        message = ip + "不是正确的IP地址";
                        break;
                    }
                }
                ipSegmBuffer.append(ipItem).append(",");
            }else{//零散IP
                if(!CheckIpUtil.isIpValid(ipItem)){
                    message = ipItem + "不是正确的IP地址";
                    break;
                }
                ipSetBuffer.append(ipItem).append(",");
            }
        }
        //如果格式验证正确，就去掉最后的逗号
        if(message == null) {
            if(ipSegmBuffer.length() >1){
                ipSegmBuffer.deleteCharAt(ipSegmBuffer.length() - 1);
            }
            this.ipSegm = ipSegmBuffer.toString();
            if(ipSetBuffer.length() > 1){
                ipSetBuffer.deleteCharAt(ipSetBuffer.length() - 1);
            }
            this.ipSet = ipSetBuffer.toString();
        }
        return message;
    }

    /**
     * 识别IP是以什么字符分隔
     * @param ip
     * @return
     */
    private char querySplitChar(String ip){
        if(ip.indexOf(SPLITMARK_LINE) > 0) return SPLITMARK_LINE;
        else if(ip.indexOf(SPLITMARK_BOTLINE) > 0) return SPLITMARK_BOTLINE;
        else return '0';
    }

    /**
     * 检查是否是IP段,IP段以’-‘或者'~'(波浪符)分隔。如172.28.10.172-172.28.10.192
     * @param ip
     */
    private boolean checkIsIpSegm(String ip){
        boolean isIpSegm = false;
        if(ip.indexOf(SPLITMARK_BOTLINE) > 0 && ip.indexOf(SPLITMARK_BOTLINE) == ip.lastIndexOf(SPLITMARK_BOTLINE)){
            isIpSegm = true;
        }else if(ip.indexOf(SPLITMARK_LINE) > 0 && ip.indexOf(SPLITMARK_LINE) == ip.lastIndexOf(SPLITMARK_LINE)){
            isIpSegm = true;
        }
        return isIpSegm;
    }

    /**
     * 构建前端需要的IP数组
     */
    public void buildIpsWithIp(){
        StringBuffer sb = new StringBuffer();
        if(!StringUtils.isEmpty(ipSet)){
            sb.append(ipSet);
            if(!StringUtils.isEmpty(ipSegm)){
                sb.append(",").append(ipSegm);
            }
        }else if(!StringUtils.isEmpty(ipSegm)){
            sb.append(ipSegm);
        }

        ip = sb.toString();
        ips = ip.split(COMMA);
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符等
     */
    public static String replaceSpecialStr(String str) {
        String repl = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            repl = m.replaceAll("");
        }
        return repl;
    }
    public String[] getIps() {
        return ips;
    }

    public void setIps(String[] ips) {
        this.ips = ips;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIpSet() {
        return ipSet;
    }

    public void setIpSet(String ipSet) {
        this.ipSet = ipSet;
    }

    public String getIpSegm() {
        return ipSegm;
    }

    public void setIpSegm(String ipSegm) {
        this.ipSegm = ipSegm;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }
}
